package com.sgb.goods.viewmodel.publish;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;

import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClient;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.goods.api.GoodsCallBack;
import com.sgb.goods.api.GoodsNet;
import com.sgb.goods.entity.AliProofEntity;
import com.sgb.goods.entity.VideoChangeEntity;
import com.sgb.goods.entity.VideoEntity;
import com.sgb.goods.utils.base.GoodsSdk;
import com.sgb.goods.utils.base.viewmodel.BaseViewModel;
import com.sgb.goods.view.adapter.publish.VideoAdapter;
import com.sgb.goods.view.adapter.publish.pop.VideoSelectPopWindow;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

/**
 * 商品发布-视频上传
 * 选一个上传一个
 * @author cyj
 */
final public class VideoUploadViewModel extends BaseViewModel {

    /** 视频适配器 */
    public VideoAdapter videoAdapter;
    /** 视频弹窗 */
    private VideoSelectPopWindow videoSelectPopWindow;
    //视频 & 上传视频
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private VODUploadClient uploader;
    private AliProofEntity aliProofEntity;
    /** 上传的视频列表 */
    public List<VideoChangeEntity> videoList = new ArrayList<>();

    // 用户选择的视频对象。一次可能选择多个。它会存储所有的视频选择，然后与图片上传一样在发布商品前进行上传，使用代理获得上传结果
    public List<LocalMedia> locVideoList = new ArrayList<>();

    public VideoUploadViewModel() {
        videoAdapter = new VideoAdapter(application, 5);
    }

    /** 获取视频选择弹窗 */
    public VideoSelectPopWindow getVideoSelectPopWindow() {
        if (videoSelectPopWindow == null) {
            // 初始化视频相关服务
            sensorManager = (SensorManager) application.getSystemService(Context.SENSOR_SERVICE);
            sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
            uploader = new VODUploadClientImpl(application);
            initListener();

            // 弹窗初始化
            videoSelectPopWindow = new VideoSelectPopWindow(GoodsSdk.getInstance().getTopActivity());
            videoSelectPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            videoSelectPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            videoSelectPopWindow.setOnResultClick((key1, key2, key3) -> {
                // 选择视频
                VideoEntity videoEntity = (VideoEntity) key2;
                videoAdapter.addData(videoEntity);
                // 创建上传视频文件对象并添加到 uploader
                VodInfo vodInfo = new VodInfo();
                vodInfo.setTitle(videoEntity.title);
                vodInfo.setDesc("商品视频");
                vodInfo.setCateId((int) System.currentTimeMillis());
                vodInfo.setTags(null);
                uploader.addFile(videoEntity.url, vodInfo);
                // 获取上传凭证
                getVideoParams();
            });
        }
        return videoSelectPopWindow;
    }

    /**
     * 视频选择入口 此方法为用户选择视频库的视频后返回到 activityResult 然后设置此方法，并将数据填充到弹窗的适配器中
     * @param localMediaData    用户选择的视频对象，一次可能选择多个
     */
    public void setLocalMediaData(List<LocalMedia> localMediaData) {
        if(null == localMediaData || localMediaData.size() <= 0) {
            // 一个视频都没有选择
            return;
        }
        videoSelectPopWindow.setData(localMediaData, videoAdapter.getDataSize() - 1);
    }

    /** 打开弹窗 */
    public void openPopWindow(View view, int index) {
        if (videoAdapter.getDataSize() != 5) {
            //重置弹窗数据
            getVideoSelectPopWindow().setDataRest(PictureConfig.TYPE_VIDEO);
            getVideoSelectPopWindow().showAsDropDown(view, 0, 0);
        } else {
            MToast.showToast(application.getApplicationContext(), "最多选择五个视频");
        }
    }

    /**
     * 获取上传成功的视频id集合
     * 注意：组装最终上传成功的视频，及时某个视频上传失败/异常不中断商品发布且不影响业务继续流转，用户可在编辑时再次上传
     */
    public List<VideoChangeEntity> getVideoChangeEntityList() {
        //视频实体转换
        List<VideoChangeEntity> list = new ArrayList<>();
        for (int i = 0; i < videoAdapter.getDataSize(); i++) {
            VideoChangeEntity entity = new VideoChangeEntity();
            if(i == 0) {
                entity.type = 1;
            }
            entity.videoName = videoAdapter.getData().get(i).title;
            entity.videoId = videoAdapter.getData().get(i).videoId;
            list.add(entity);
        }
        return list;
    }

    @Override
    public void onResume(@NonNull @NotNull LifecycleOwner owner) {
        if(null != sensorManager) {
            Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    public void onPause(@NonNull @NotNull LifecycleOwner owner) {
        if(null != sensorManager) {
            sensorManager.unregisterListener(sensorEventListener);
            JCVideoPlayer.releaseAllVideos();
        }
    }

    /**
     * 当 activity 被销毁前应该关闭所有弹窗，并释放资源
     */
    @Override
    public void onDestroy(@NonNull @NotNull LifecycleOwner owner) {
        // 释放弹窗资源
        videoSelectPopWindow = null;
        // 释放视频资源
        if(null != sensorManager) {
            sensorManager.unregisterListener(sensorEventListener);
            JCVideoPlayer.releaseAllVideos();
        }
    }

    /** 获取上传凭证并上传视频 */
    public void getVideoParams() {
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().getVideoParams().enqueue(new GoodsCallBack<BaseEntity<AliProofEntity>>() {
            @Override
            public void onSuccess(BaseEntity<AliProofEntity> data) {
                aliProofEntity = data.getData();
                if(null != aliProofEntity) {
                    showLoading();
                    uploader.start();
                }
            }

            @Override
            public void onFail() {
                super.onFail();
                MToast.showToast(application, "上传失败");
            }
        });
    }

    private void initListener() {
        uploader.init(new VODUploadCallback() {
            @Override
            public void onUploadSucceed(UploadFileInfo info) {
                MLog.e("onUploadSucceed", "\n 上传成功. \n name：" + info.getObject() + " \n title：" + info.getVodInfo().getTitle());
                cancelLoading();
                videoAdapter.getData().get(videoAdapter.getDataSize() - 1).videoId = aliProofEntity.videoId;
            }

            @Override
            public void onUploadFailed(UploadFileInfo info, String code, String message) {
                cancelLoading();
            }

            @Override
            public void onUploadTokenExpired() {
                uploader.resumeWithAuth(aliProofEntity.uploadAuth);
            }

            @Override
            public void onUploadStarted(UploadFileInfo uploadFileInfo) {
                uploader.setUploadAuthAndAddress(uploadFileInfo, aliProofEntity.uploadAuth, aliProofEntity.uploadAddress);
            }
        });
    }
}
